from apscheduler.schedulers.blocking import BlockingScheduler
from loguru import logger
from pathlib import Path
import pandas as pd
from gypb.apps.data_sync import sync_risk_factors, sync_constituent_weight, get_hfw_net_value, upload_hfw_net_value, get_hfw_products, upload_hfw_products,upload_nv_to_hfv
from gypb.db import get_rqapi
import rqdatac

rqapi = get_rqapi()

from gypb.config import settings
basedir = settings.custom_dir
if not basedir:
    basedir = Path.home().joinpath(".gypb")

# 配置日志记录，指定日志文件的路径
log_file_path = Path(basedir).joinpath("apscheduler.log")
logger.add(log_file_path)


# 定义定时任务函数
def gypb_jobs():
    try:
        today = pd.Timestamp.now().normalize()
        if today.day == 1:
            page = 1
            while True:
                hfn_df = get_hfw_products(page=page, pagesize=1000)
                if hfn_df.empty:
                    break
                logger.info(f"正在更新第{(page - 1) * 1000 + 1}至{page * 1000}只产品信息")
                upload_hfw_products(hfn_df)
                page += 1
            logger.info("已更新火富牛产品列表")
        if rqdatac.is_trading_date(today):
            t_1_tradeday = pd.Timestamp(rqdatac.get_previous_trading_date(today))
            t_2_tradeday = pd.Timestamp(rqdatac.get_previous_trading_date(today,2))
            t_3_tradeday = pd.Timestamp(rqdatac.get_previous_trading_date(today,3))
            if t_2_tradeday.weekofyear != t_1_tradeday.weekofyear:
                # 同步华安核心净值
                upload_hfw_net_value(get_hfw_net_value("ASD96A"))
                logger.info("已同步华安核心净值")
            if t_3_tradeday.weekofyear != t_2_tradeday.weekofyear:
                # 上传千象成长11号、明泽泰达科创优选2号、深圳青岸元鼎臻选105号OTC净值到火富牛
                upload_nv_to_hfv(["SQN990","SND029","SAAC57"],t_3_tradeday,t_3_tradeday)
                logger.info("已上传千象明泽青岸105净值")
            sync_constituent_weight(t_1_tradeday, t_1_tradeday, objects=["000300.SSE", "000905.SSE", "000852.SSE"])
            sync_risk_factors(t_1_tradeday, t_1_tradeday)
            logger.info(f"已同步{t_1_tradeday}的成分股数据和风险因子数据")
    except Exception as e:
        logger.error(f"执行 gypb_jobs 时出现异常: {e}")


def test_job():
    try:
        logger.info(f"start job at {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}")
    except Exception as e:
        logger.error(f"执行 test_job 时出现异常: {e}")


def start_scheduler():
    try:
        scheduler = BlockingScheduler()
        # 设置定时任务，每天凌晨执行
        scheduler.add_job(gypb_jobs, 'cron', hour=5, minute=30,misfire_grace_time=600)  # 风险因子数据每天5点10分更新
        # scheduler.add_job(test_job, 'cron', hour=6, minute=30,misfire_grace_time=600)
        logger.info("已添加任务")
        scheduler.start()
    except Exception as e:
        logger.error(f"调度器启动时出现异常: {e}")


if __name__ == "__main__":
    start_scheduler()
    # gypb_jobs()
    # upload_hfw_net_value(get_hfw_net_value("ASD96A"))